package net.deiangi.graphs.core;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * User: Deian
 * Date: Oct 30, 2009
 * Time: 11:14:16 PM
 */
public class Graph {
    public List<Node> nodes;
    public List<Edge> edges;

    public Graph() {
        clear();
    }

    public void clear() {
        nodes = new ArrayList<Node>();
        edges = new ArrayList<Edge>();
    }

    public void addEdge(String f, String t, int weight) {
        int fi = indexOfNode(f, true);
        int ti = indexOfNode(t, true);

        Edge e = new Edge(fi, ti, weight);
        edges.add(e);
        Node from = nodes.get(fi);
        from.to.add(e);
    }

    public int indexOfNode(String a, boolean canAdd) {
        int i = -1;
        int found = -1;
        for (Node n : nodes) {
            i++;
            if (n.name.equalsIgnoreCase(a)) {
                found = i;
                break;
            }
        }
        if (found == -1 && canAdd) {
            nodes.add(new Node(a, 100, 100));
            found = nodes.size() - 1;
            nodes.get(found).i = found;
        }
        return found;
    }

    public void load(String src) {
        String[] params = src.replaceAll("[ \t\n\r]", "").split(";");
        for (String p : params) {
            String[] nv = p.split("=");
            if (nv[0].equalsIgnoreCase("g")) {
                String[] links = nv[1].split(",");
                for (String link : links) {
                    String[] nodeInfo = link.split("/");
                    String[] nodes = nodeInfo[0].split("-");
                    int w = (nodeInfo.length == 2) ? Integer.parseInt(nodeInfo[1]) : 50;
                    addEdge(nodes[0], nodes[1], w);
                }
            } else if (nv[0].equalsIgnoreCase("c")) {
                String[] ns = nv[1].split(",");
                for (String n : ns) {
                    //String[] nodeInfo = n.split(",");
                    int i = indexOfNode(n, true);
                    nodes.get(i).fixed = true;
                }
            }
        }
        System.out.printf("added %d nodes and %d edges\n", nodes.size(), edges.size());
    }

    public void randomize(Dimension d) {
        for (Node n : nodes) {
            n.x = d.getWidth() * Math.random();
            n.y = d.getHeight() * Math.random();
        }
    }
}

